
function resetFileUploadForm() {
    $('#fileupload-modal-title').html('Image Upload');
    $('#fileupload-save-btn').html('Create Image Upload Input');
    
    $('#fileupload-type').val('image');
    $('#fileupload-guideline').val('none');
    
    $('#fileupload-form').find('.image-control').slideDown();
    if( $('#fileupload-resize').is(':checked') ) {
        $('#fileupload-form').find('.resize-control').slideDown();
    } else {
        $('#fileupload-form').find('.resize-control').hide();
    }
    $('#fileupload-form').find('.guideline-control').slideUp();
    
    $('#fileupload-file-types').tagsinput('destroy');
    $('#fileupload-file-types').val('jpg,png,gif');
    $('#fileupload-file-types').tagsinput();
    
    $('#fileupload-label-text').val('');
    $('#fileupload-name').val('');
    $('#fileupload-id').val('');
}

function toButtonUpload() {
    $('#fileupload-modal-title').html('Button Upload');
    $('#fileupload-save-btn').html('Create Button Upload Input');
    
    $('#fileupload-type').val('button');
    $('#fileupload-guideline').val('none');
    
    $('#fileupload-form').find('.image-control').slideUp();
    $('#fileupload-form').find('.guideline-control').slideUp();
    
    $('#fileupload-file-types').tagsinput('destroy');
    $('#fileupload-file-types').val('doc,docx,xls,xlsx,ppt,pptx');
    $('#fileupload-file-types').tagsinput();
}

function toFileUpload() {
    $('#fileupload-modal-title').html('File Upload');
    $('#fileupload-save-btn').html('Create File Upload Input');
    
    $('#fileupload-type').val('file');
    $('#fileupload-guideline').val('none');
    
    $('#fileupload-form').find('.image-control').slideUp();
    $('#fileupload-form').find('.guideline-control').slideUp();
    
    $('#fileupload-file-types').tagsinput('destroy');
    $('#fileupload-file-types').val('doc,docx,xls,xlsx,ppt,pptx');
    $('#fileupload-file-types').tagsinput();
}

function toMultipleFileupload() {
    $('#fileupload-modal-title').html('Multiple Files Upload');
    $('#fileupload-save-btn').html('Create Multi-Files Upload Input');
    
    $('#fileupload-type').val('multiple');
    $('#fileupload-guideline').val('none');
    
    $('#fileupload-form').find('.image-control').slideDown();
    if( $('#fileupload-resize').is(':checked') ) {
        $('#fileupload-form').find('.resize-control').slideDown();
    } else {
        $('#fileupload-form').find('.resize-control').hide();
    }
    $('#fileupload-form').find('.guideline-control').slideUp();
    
    $('#fileupload-file-types').tagsinput('destroy');
    $('#fileupload-file-types').val('jpg,png,gif,doc,docx,xls,xlsx,ppt,pptx');
    $('#fileupload-file-types').tagsinput();
    
}

$(function() {

    // initialize tags-input
    $('#fileupload-file-types').tagsinput();
    
    // validation rules
    var rules = {};
    rules['label']                          = set_rules('label', 'label', 'required|maxlength[6]');
    rules['label-text']                     = set_rules('label-text', 'label-text', 'required|maxlength[25]');
    rules['bold-label']                     = set_rules('bold-label', 'bold-label', 'maxlength[25]');
    rules['name']                           = set_rules('name', 'name', 'required|maxlength[50]');
    rules['id']                             = set_rules('id', 'id', 'required|maxlength[50]');
    rules['type']                           = set_rules('type', 'type', 'maxlength[25]');
    rules['width']                          = set_rules('width', 'width', 'required|maxlength[5]');
    rules['height']                         = set_rules('height', 'height', 'required|maxlength[5]');
    rules['file-types']                     = set_rules('file-types', 'file-types', 'required');
    rules['show-list']                      = set_rules('show-list', 'show-list', 'maxlength[25]');
    rules['searchable']                     = set_rules('searchable', 'searchable', 'maxlength[25]');
    rules['show-api']                       = set_rules('show-api', 'show-api', 'maxlength[25]');
    rules['guideline']                      = set_rules('guideline', 'guideline', 'required|maxlength[50]');
    rules['guideline-title']                = set_rules('guideline-title', 'guideline-title', 'required|maxlength[50]');
    rules['guideline-text']                 = set_rules('guideline-text', 'guideline-text', 'required|maxlength[255]');
    rules['horizontal-size']                = set_rules('horizontal-size', 'horizontal-size', 'required|maxlength[25]');
    rules['position']                       = set_rules('position', 'position', 'required|maxlength[25]');

    // fieldset form validation
    $("#fileupload-form").validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });
    
    resetFileUploadForm();
    
    // show/hide label controls
    $('#fileupload-label').change(function() {
        if( $(this).val() === 'none' ) {
            $('#fileupload-form').find('.label-control').slideUp();
        } else {
            $('#fileupload-form').find('.label-control').slideDown();
        }
    });
    
    // auto fill-up text name, id and placeholder using label text
    $('#fileupload-label-text').change(function() {
        var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
        ( $('#fileupload-name').val() === '' || $('#fileupload-name').val() === undefined ) ? $('#fileupload-name').val(textLabel) : '';
        ( $('#fileupload-id').val() === '' || $('#fileupload-id').val() === undefined ) ? $('#fileupload-id').val(textLabel) : '';
    });
    
    // auto fill-up text name, id and placeholder using label name
    $('#fileupload-name').change(function() {
        if( $('#fileupload-label').val() === 'none' ) {
            var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
            ( $('#fileupload-id').val() === '' || $('#fileupload-id').val() === undefined ) ? $('#fileupload-id').val(textLabel) : '';
        }
    });
    
    // show/hide guideline controls
    $('#fileupload-guideline').change(function() {
        if( $(this).val() === 'none' ) {
            $('#fileupload-form').find('.guideline-control').slideUp();
        } else if(  $(this).val() === 'label' ) {
            $('#fileupload-form').find('.guideline-control').slideDown();
            $('#fileupload-guideline-title-container').slideUp();
        } else {
            $('#fileupload-form').find('.guideline-control').slideDown();
        }
    });
    
    // show/hide controls
    $('#fileupload-type').change(function() {
        if( $(this).val() === 'image' ) {
            resetFileUploadForm();
        }
        if( $(this).val() === 'file' ) {
            toFileUpload();
        }
        if( $(this).val() === 'button' ) {
            toButtonUpload();
        }
        if( $(this).val() === 'multiple' ) {
            toMultipleFileUpload();
        }
    });
    
    // show/hide resize controls
    $('#fileupload-resize').change(function() {
        if( $(this).is(':checked') ) {
            $('#fileupload-form').find('.resize-control').slideDown();
        } else {
            $('#fileupload-form').find('.resize-control').slideUp();
        }
    });
    
    $('#fileupload-save-btn').click(function(event) {
        event.preventDefault();
        $('#fileupload-form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#fileupload-form').valid()) {

            var values = $('#fileupload-form').serializeJSON();
            
            // label
            var label                   = ( values['label'] !== undefined && values['label'] !== '' ) ? values['label'] : '';
            var labelPosition           = ( label !== '' || label !== 'none' ) ? ' align-' + label : 'none';
            var labelText               = ( values['label-text'] !== undefined && values['label-text'] !== '' ) ? values['label-text'] : '';
            
            // field data
            var fieldName               = ( values['name'] !== undefined && values['name'] !== '' ) ? values['name'] : '';
            var fieldId                 = ( values['id'] !== undefined && values['id'] !== '' ) ? values['id'] : '';
//            var placeholder             = ( values['placeholder'] !== undefined && values['placeholder'] !== '' ) ? ' placeholder="' +values['placeholder']+ '"' : '';
            var type                    = ( values['type'] !== undefined && values['type'] !== '' ) ? values['type'] : '';
            
            // image
            var resize                  = ( values['resize'] !== undefined && values['resize'] !== '' ) ? true : false;
            var width                   = ( values['width'] !== undefined && values['width'] !== '' ) ? values['width'] : '';
            var height                  = ( values['height'] !== undefined && values['height'] !== '' ) ? values['height'] : '';
            var fileTypes               = ( values['file-types'] !== undefined && values['file-types'] !== '' ) ? values['file-types'] : '';

            // guideline
            var guideline               = ( values['guideline'] !== undefined && values['guideline'] !== '' ) ? values['guideline'] : '';
            var guidelineTitle          = ( values['guideline-title'] !== undefined && values['guideline-title'] !== '' ) ? values['guideline-title'] : '';
            var guidelineText           = ( values['guideline-text'] !== undefined && values['guideline-text'] !== '' ) ? values['guideline-text'] : '';
            
            // size and position
            var horizontalSize          = ( values['horizontal-size'] !== undefined && values['horizontal-size'] !== '' ) ? ' ' + values['horizontal-size'] : '';
            var verticalSize            = ( values['vertical-size'] !== undefined && values['vertical-size'] !== '' )? ' ' + values['vertical-size'] : '';
            var position                = ( values['position'] !== undefined && values['position'] !== '' ) ? ' ' + values['position'] : '';

            // validations
            var validations             = values['validations'];
            var required                = $.inArray('required', validations) !== -1 ? ' required="true" ' : ' ';
            var requiredLabel           = ( $.inArray('required', validations) !== -1 && values['label'] !== '' && values['label'] !== 'none') ? ' *' : '';

            var markup = '';
            var list = $('<li class="form-group row"></li>');
            markup += '<button type="button" class="close" aria-hidden="true">&times;</button>\n';
            markup += '<label for="' +fieldId+ '" class="control-label' +labelPosition+ ' col-3">\n';
            markup += labelText + requiredLabel + '\n';
            markup += '<br><small>' +guidelineText+ '</small>\n';
            markup += '</label>\n';
            markup += '<div class="control-group col-9">\n';
            markup += '<div class="input-size' + horizontalSize + position + '">\n';
            
            if( type === 'button' ) {
                markup += '<div class="fileinput fileinput-new" data-provides="fileinput">\n';
                markup += '<span class="btn btn-default btn-file"><span class="fileinput-new">Select file</span><span class="fileinput-exists">Change</span><input type="file" name="' +fieldName+ '" id="' +fieldId+ '"' + required + '></span>\n';
                markup += '<span class="fileinput-filename"></span>\n';
                markup += '<a href="#" class="close fileinput-exists" data-dismiss="fileinput" style="float: none">&times;</a>\n';
                markup += '</div>\n';
            }
            
            if( type === 'file' ) {
                markup += '<div class="fileinput fileinput-new input-group" data-provides="fileinput">\n';
                markup += '<div class="form-control" data-trigger="fileinput"><i class="glyphicon glyphicon-file fileinput-exists"></i> <span class="fileinput-filename"></span></div>\n';
                markup += '<span class="input-group-addon btn btn-default btn-file"><span class="fileinput-new">Select file</span><span class="fileinput-exists">Change</span><input type="file" name="' +fieldName+ '" id="' +fieldId+ '"' + required + '></span>\n';
                markup += '<a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>\n';
                markup += '</div>\n';
            }
            
            if( type === 'image') {
                markup += '<div class="fileinput fileinput-new" data-provides="fileinput">\n';
                markup += '<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">\n';
                markup += '<img src="' + base_url + 'resources/images/no_image.gif" data-src="' + base_url + 'resources/images/no_image.gif" alt="image">\n';
                markup += '</div>\n';
                markup += '<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>\n';
                markup += '<div>\n';
                markup += '<span class="btn btn-default btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="' +fieldName+ '" id="' +fieldId+ '"' + required + '></span>\n';
                markup += '<a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>\n';
                markup += '</div>\n';
                markup += '</div>\n';
            }
            
            if( type === 'multiple' ) {
                markup += '<div id="' +fieldId+ '">\n';
                markup += '<p>Your browser doesn\'t have Flash, Silverlight or HTML5 support.</p>';
                markup += '</div>\n';
            }

            markup += '</div>\n';
            markup += '</div>\n';
            
            list.html(markup);
            list.data('controls', values);
            
            $('#form-sortable li:first-child fieldset:first-child ul').prepend(list);
            
            if( type === 'multiple') {
                $('#' + fieldId).pluploadQueue({
                    // General settings
                    runtimes: 'html5,flash,silverlight,html4',
                    url: base_url + "fileuploader/upload",
                    chunk_size: '1mb',
                    rename: true,
                    dragdrop: true,
                    filters: {
                        // Maximum file size
                        max_file_size: '10mb',
                        // Specify what files to browse for
                        mime_types: [
                            {title: "Image files", extensions: "jpg,gif,png"},
                            {title: "Zip files", extensions: "zip"}
                        ]
                    },
                    // Resize images on clientside if we can
                    resize: {
                        width: 200,
                        height: 200,
                        quality: 90,
                        crop: true // crop to exact dimensions
                   },
                    // Flash settings
                    flash_swf_url: '/plupload/js/Moxie.swf',
                    // Silverlight settings
                    silverlight_xap_url: '/plupload/js/Moxie.xap'
                });
            }
            
            $('#fileupload-modal').modal('hide');

        }
        
        // submit form for validation purposes
        $('#fileupload-form').submit();

    });
    
    // generic file upload button
    $('#generic-fileupload-btn').click(function() {
        resetFileUploadForm();
        $('#fileupload-modal').modal({
            width: '95%'
        });
    });
    
    // button upload button
    $('#button-upload-btn').click(function() {
        resetFileUploadForm();
        toButtonUpload();
        $('#fileupload-modal').modal({
            width: '95%'
        });
    });
    
    // file upload button
    $('#file-upload-btn').click(function() {
        resetFileUploadForm();
        toFileUpload();
        $('#fileupload-modal').modal({
            width: '95%'
        });
    });
    
    // image upload button
    $('#image-upload-btn').click(function() {
        resetFileUploadForm();
        $('#fileupload-modal').modal({
            width: '95%'
        });
    });
    
});

